<template>
  <el-select
    style="width: 100%"
    clearable
    filterable
    :placeholder="placeholder"
    v-model="selected"
    @change="select"
    @clear="clear"
  >
    <el-option v-for="item in dataList" :key="item._id" :label="item.userName" :value="item._id" />
  </el-select>
</template>

<script setup lang="ts" name="selectFilter">
import { computed, onMounted, ref } from "vue";
import { useDataStore } from "@/stores/modules/data";
import { Md5 } from "ts-md5";
import apiService from "@/api/services/apiService";
import { DataState } from "@/enums/sysEnum";

const paramKey = ref();
const dataStore = useDataStore();
const dataList = computed(() => {
  if (paramKey.value) {
    return dataStore.getCommonDataByName(paramKey.value);
  } else {
    return dataStore.userList;
  }
});
const selected = ref<{ [key: string]: any }>({});

interface SelectFilterProps {
  param?: any;
  dataKey?: String;
  value?: String;
  placeholder?: String;
}

const props = withDefaults(defineProps<SelectFilterProps>(), {
  placeholder: () => "请选择",
  value: () => ""
});

onMounted(() => {
  selected.value = props.value;
  if (props.param) {
    paramKey.value = Md5.hashStr(JSON.stringify(props.param));
    let condition = { ...props.param, state: DataState.DEFAULT };
    dataStore.findList(paramKey.value, () => apiService.find("users", condition));
  } else {
    dataStore.findUserList();
  }
});

const refreshParams = (params: any) => {
  if (params) {
    paramKey.value = Md5.hashStr(JSON.stringify(params));
    let condition = { ...params, state: DataState.DEFAULT };
    dataStore.findList(paramKey.value, () => apiService.find("users", condition));
  } else {
    dataStore.findUserList();
  }
};

const select = () => {
  emit("change", selected.value);
};

const clear = () => {
  emit("clear");
};

// emit
const emit = defineEmits<{
  change: [value: any];
  clear;
}>();

defineExpose({
  refreshParams
});
</script>

<style scoped lang="scss"></style>
